<template>
  <div>
    <!-- 订货单审核-->
    <TopFilter :list="topFilterList" ref="top" :cols="3" @filterChange="changeHandle" @onCollapse="collapseHandle" :labelWidth="110" @resetChange="resetChange"></TopFilter>

    <Spin :spinning="exportLoading" tip="Loading...">
      <FilterTables
        ref="table"
        :columns="columns"
        :fetchapi="fetchApi"
        :params="fetchParams"
        :datakey="'records'"
        columnsRef="purchaseOrder"
        :onSyncTableData="syncTableData"
        :pageSize="200"
        :pageSizesArray="[200, 500]"
        :onRowSelectChange="selectChangeHandle"
        :onColumnsChange="(columns) => (this.columns = columns)"
      >
        <template slot="controls">
          <multiuse-button size="small" type="primary" :click="addHandle.bind(this, 8)" :disabled="isOpen">保存 </multiuse-button>
          <multiuse-button size="small" type="primary" :click="addHandle.bind(this, 1)" :disabled="isOpen">审核确认 </multiuse-button>
          <multiuse-button size="small" type="primary" :click="addHandle.bind(this, 2)" :disabled="isOpen">订单作废 </multiuse-button>
          <multiuse-button size="small" type="primary" :click="addHandle.bind(this, 3)" :disabled="isOpen">取消审核 </multiuse-button>
          <multiuse-button size="small" type="primary" @click="addHandle(4)">导 出</multiuse-button>
          <multiuse-button size="small" type="primary" @click="addHandle(5)">导入发运通知</multiuse-button>
          <multiuse-button size="small" type="primary" @click="addHandle(6)" :disabled="isOpen">资金调整</multiuse-button>
          <multiuse-button size="small" type="primary" @click="addHandle(7)" :disabled="isOpen">地址调整</multiuse-button>
        </template>
      </FilterTables>
    </Spin>

    <BaseDialog :visible.sync="isFundType" :title="'资金调整'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <fundTypeAdjustment @close="FundTypeClose" :list="selectList" />
    </BaseDialog>
    <BaseDialog :visible.sync="isAddress" :title="'地址调整'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <addressAdjustment @close="AddressClose" :list="selectList" />
    </BaseDialog>
    <Drawer :visible.sync="detailVisible" :title="'订单信息'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }" width="72%">
      <detailModel :rowData="formData" @close="detailCloseHandler" />
    </Drawer>
    <BaseDialog :visible.sync="isbill" :title="'选择三方票据'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <BillDetail :rowData="billData" @close="billclose" />
    </BaseDialog>
    <BaseDialog :visible.sync="importVisible" :title="'导入'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <importFiles @close="importcloseHandler" />
    </BaseDialog>
    <BaseDialog :visible.sync="isreject" :title="'作废订单'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <reject :list="selectList" @close="rejectClose" />
    </BaseDialog>
    <BaseDialog :visible.sync="isFinanceReject" :title="'作废订单'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <FinanceReject :list="selectList" @close="financeRejectClose" />
    </BaseDialog>
  </div>
</template>
<script>
import { confirmOrder, excelList, queryList, vehicleConfiguration, allAccountType, cancelOrder, saveOrder } from '@/api/omSaleP/OrderManagement/PurchaseOrder/index.js';
import detailModel from './detailModel';
import importFiles from './importFiles';
import fundTypeAdjustment from './fundTypeAdjustment';
import addressAdjustment from './addressAdjustment';
import { dictionary } from '@/utils/dictMixin';
import BillDetail from './BillDetail';
import FinanceReject from './FinanceReject';
import reject from './reject';
import { exportExcelFile } from '@/utils';
import { getBrandListOEM, getSeriesListOEM, getModelListOEM, getPackageListOEM, getOptionListDictOEM, getWcolorList, getIcolorList } from '@/api/common/cars/masterDataCars';
export default {
  name: 'purchaseOrder',
  data() {
    this.BaseTable = null;
    return {
      topFilterList: this.createdFrom(),
      columns: this.createdTable(),
      fetchApi: queryList,
      fetchParams: {
        xhrAbort: true,
        orderStatus: 21091001,
      },
      pageSize: 20,
      pageSizesArray: [500, 20, 30, 40, 100],
      formData: {},
      exportLoading: false,
      detailVisible: false,
      importVisible: false,
      isFundType: false,
      isAddress: false,
      isOpen: true,
      selectList: [],
      isbill: false,
      billData: {},
      isFinanceReject: false,
      isreject: false,
    };
  },
  components: {
    detailModel,
    importFiles,
    fundTypeAdjustment,
    addressAdjustment,
    BillDetail,
    reject,
    FinanceReject,
  },
  mixins: [dictionary],
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  created() {
    // this.getvehicleList();
    this.initAllAccountType();
    this.getcarList();
    this.getDictBrandList();
    this.getColors();
    this.getIColors();
  },
  watch: {
    importVisible(newval, oldval) {
      if (!newval) {
        this.fetchParams = Object.assign({}, this.fetchParams);
      }
    },
  },
  mounted() {
    this.fetchParams = Object.assign({}, this.fetchParams, { xhrAbort: false });
  },
  methods: {
    resetFormatterNumber(arr) {
      for (let i = 0; i < arr.length; i++) {
        let afterDiscountAmount = arr[i].afterDiscountAmount !== null ? Number(arr[i].afterDiscountAmount.toString().replaceAll(',', '')).toFixed(2) : Number(0).toFixed(2);
        // let singleAmount = arr[i].singleAmount !== null ? Number(arr[i].singleAmount.toString().replaceAll(',', '')).toFixed(2) : Number(0).toFixed(2);
        // let discountAmount = arr[i].discountAmount !== null ? Number(arr[i].discountAmount.toString().replaceAll(',', '')).toFixed(2) : Number(0).toFixed(2);
        // let singleRebateAmount = arr[i].singleRebateAmount !== null ? Number(arr[i].singleRebateAmount.toString().replaceAll(',', '')).toFixed(2) : Number(0).toFixed(2);
        // let buildRebateAmount = arr[i].buildRebateAmount !== null ? Number(arr[i].buildRebateAmount.toString().replaceAll(',', '')).toFixed(2) : Number(0).toFixed(2);
        arr[i].afterDiscountAmount = afterDiscountAmount;
        // arr[i].singleAmount = singleAmount;
        // arr[i].discountAmount = discountAmount;
        // arr[i].singleRebateAmount = singleRebateAmount;
        // arr[i].buildRebateAmount = buildRebateAmount;
      }
      return arr;
    },
    resetChange(params) {
      this.topFilterList.find((item) => item.fieldName === 'seriesId').initialValue = '';
      this.topFilterList.find((item) => item.fieldName === 'seriesId').itemList = [];
      this.topFilterList.find((item) => item.fieldName === 'modelId').initialValue = '';
      this.topFilterList.find((item) => item.fieldName === 'modelId').itemList = [];
      this.topFilterList.find((item) => item.fieldName === 'packageId').initialValue = '';
      this.topFilterList.find((item) => item.fieldName === 'packageId').itemList = [];
      this.topFilterList.find((item) => item.fieldName === 'optionId').initialValue = '';
      this.topFilterList.find((item) => item.fieldName === 'optionId').itemList = [];
      this.fetchParams = Object.assign({}, this.fetchParams);
    },
    syncTableData(value) {
      if (this.$refs.table) {
        const arr = value.filter((item) => item.isRebate === 10041002);
        this.changeIsRebate(arr, true);
        const arr1 = value.filter((item) => item.transportType === 24091002);
        this.changeIsCustom(arr1, true);
      }
    },
    changeIsCustom(row, disabled) {
      for (let i in row) {
        // this.$set(row[i], `${'cityName'}IsEdit`, Boolean(disabled));
        this.$set(row[i], `${'linkMan'}IsEdit`, Boolean(disabled));
        this.$set(row[i], `${'linkPhone'}IsEdit`, Boolean(disabled));
      }
    },
    async getDictBrandList() {
      const res = await getBrandListOEM();
      if (res.resultCode === 200) {
        //console.log(this.topFilterList, 'this.topFilterList');
        this.topFilterList.find((item) => item.fieldName === 'brandId').itemList = res.data.map((x) => ({ value: x.brandId, text: x.brandName }));
        // this.topFilterList = [...this.topFilterList]
      }
    },
    async changeBrandSelect(brandsid) {
      // if (!brandsid) {
      this.topFilterList.find((item) => item.fieldName === 'seriesId').initialValue = '';
      this.topFilterList.find((item) => item.fieldName === 'seriesId').itemList = [];
      this.topFilterList.find((item) => item.fieldName === 'modelId').initialValue = '';
      this.topFilterList.find((item) => item.fieldName === 'modelId').itemList = [];
      this.topFilterList.find((item) => item.fieldName === 'packageId').initialValue = '';
      this.topFilterList.find((item) => item.fieldName === 'packageId').itemList = [];
      this.topFilterList.find((item) => item.fieldName === 'optionId').initialValue = '';
      this.topFilterList.find((item) => item.fieldName === 'optionId').itemList = [];
      // } else {
      if (brandsid) {
        const res = await getSeriesListOEM(brandsid);
        if (res.resultCode === 200) {
          this.topFilterList.find((item) => item.fieldName === 'seriesId').itemList = res.data.map((x) => ({ value: x.seriesId, text: x.seriesName }));
        }
      }
    },
    async changeSeriesSelect(seriessid) {
      const brandsid = this.topFilterList.find((item) => item.fieldName === 'brandId').initialValue;
      /* if (!brandsid || !seriessid) {
        this.topFilterList.find(item=>item.fieldName==='modelId').initialValue = '';
        this.topFilterList.find(item=>item.fieldName==='modelId').itemList = [];
        this.topFilterList.find(item=>item.fieldName==='packageId').initialValue = '';
        this.topFilterList.find(item=>item.fieldName==='packageId').itemList = [];
      } else { */
      if (brandsid && seriessid) {
        this.topFilterList.find((item) => item.fieldName === 'modelId').initialValue = '';
        this.topFilterList.find((item) => item.fieldName === 'modelId').itemList = [];
        this.topFilterList.find((item) => item.fieldName === 'packageId').initialValue = '';
        this.topFilterList.find((item) => item.fieldName === 'packageId').itemList = [];
        this.topFilterList.find((item) => item.fieldName === 'optionId').initialValue = '';
        this.topFilterList.find((item) => item.fieldName === 'optionId').itemList = [];
        const res = await getModelListOEM(brandsid, seriessid);
        if (res.resultCode === 200) {
          this.topFilterList.find((item) => item.fieldName === 'modelId').itemList = res.data.map((x) => ({ value: x.modelId, text: x.modelName }));
        }
      }
      // }
    },
    async changeModelSelect(modelId) {
      const brandsid = this.topFilterList.find((item) => item.fieldName === 'brandId').initialValue;
      const seriessid = this.topFilterList.find((item) => item.fieldName === 'seriesId').initialValue;
      this.topFilterList.find((item) => item.fieldName === 'optionId').initialValue = '';
      this.topFilterList.find((item) => item.fieldName === 'optionId').itemList = [];
      // if (!brandsid || !seriessid || !modelId) {
      this.topFilterList.find((item) => item.fieldName === 'packageId').initialValue = '';
      this.topFilterList.find((item) => item.fieldName === 'packageId').itemList = [];
      // } else {
      if (modelId) {
        const res = await getPackageListOEM(brandsid, seriessid, modelId);
        if (res.resultCode === 200) {
          this.topFilterList.find((item) => item.fieldName === 'packageId').itemList = res.data.map((x) => ({ value: x.packageId, text: x.configName }));
        }
      }
      // }
    },
    async changePackageSelect(packageId) {
      const brandsid = this.topFilterList.find((item) => item.fieldName === 'brandId').initialValue;
      const seriessid = this.topFilterList.find((item) => item.fieldName === 'seriesId').initialValue;
      // if (!brandsid || !seriessid || !modelId) {
      this.topFilterList.find((item) => item.fieldName === 'optionId').initialValue = '';
      this.topFilterList.find((item) => item.fieldName === 'optionId').itemList = [];
      // } else {
      if (packageId) {
        const res = await getOptionListDictOEM(packageId);
        if (res.resultCode === 200) {
          this.topFilterList.find((item) => item.fieldName === 'optionId').itemList = res.data.map((x) => ({ value: x.optionId, text: x.optionName }));
        }
      }
      // }
    },
    async getColors() {
      const res = await getWcolorList();
      if (res.resultCode === 200) {
        this.topFilterList.find((item) => item.fieldName === 'colorId').itemList = res.data.map((x) => ({ value: x.colorId, text: x.colorName }));
      }
    },
    async getIColors() {
      const res = await getIcolorList();
      if (res.resultCode === 200) {
        this.topFilterList.find((item) => item.fieldName === 'trimColorId').itemList = res.data.map((x) => ({ value: x.colorId, text: x.colorName }));
      }
    },
    async getcarList() {
      // let res = await vehicleConfiguration(0, { isUnlimited: 10041001 });
      // this.topFilterList.find((item) => item.fieldName === 'vehicleInfo').itemList = res.data;
    },
    async initAllAccountType() {
      const res = await allAccountType();
      if (res.resultCode === 200) {
        (res.data || []).map((x) => {
          this.topFilterList.find((item) => item.fieldName == 'accountId').itemList.push({ text: x.accountTypeName, value: x.accountId });
        });
      }
    },
    formatNumber(value) {
      value += '';
      if (value.slice(-1) === '.') return value;
      value = value.replace(/,\s+/g, '');
      const list = value.split('.');
      const prefix = list[0].charAt(0) === '-' ? '-' : '';
      let num = prefix ? list[0].slice(1) : list[0];
      let result = '';
      while (num.length > 3) {
        result = `, ${num.slice(-3)}${result}`;
        num = num.slice(0, num.length - 3);
      }
      if (num) {
        result = num + result;
      }
      console.log(`${prefix}${result}${list[1] ? `.${list[1]}` : ''}`);
      return `${prefix}${result}${list[1] ? `.${list[1]}` : ''}`;
    },
    createdFrom() {
      return [
        {
          type: 'TEXT_AREA',
          label: '结算订单编号',
          fieldName: 'doNo',
          maxlength: '10000',
          placeholder: '输入多个订单管理号时，请用英文逗号或者换行隔开（例如：单号1,单号2……）',
          maxRows: 2,
        },
        {
          type: 'SELECT',
          label: '订单明细状态',
          fieldName: 'orderStatus',
          placeholder: '请选择',
          itemList: this.createDictList('2109').filter(
            (item) => item.value == '21091001' || item.value == '21091008' || item.value == '21091009' || item.value == '21091002' || item.value == '21091003'
          ),
          initialValue: 21091001,
        },
        {
          type: 'INPUT',
          label: '订单编号',
          fieldName: 'orderNo',
          placeholder: '请输入',
        },
        {
          type: 'INPUT',
          label: '物料编码',
          width: 200,
          fieldName: 'productCode',
          placeholder: '请输入',
        },
        {
          type: 'SELECT',
          label: '订单类型',
          fieldName: 'orderType',
          placeholder: '请选择',
          itemList: this.createDictList('2105').filter((item) => item.value == '21051001' || item.value == '21051002'),
        },
        {
          type: 'SELECT',
          label: '车辆用途',
          fieldName: 'vehicleUse',
          placeholder: '请选择',
          itemList: this.createDictList('2102'),
        },
        {
          type: 'SELECT',
          label: '紧急度',
          fieldName: 'emergencyType',
          placeholder: '请选择',
          itemList: this.createDictList('2101'),
        },
        {
          type: 'SELECT',
          label: '资金类型',
          fieldName: 'accountId',
          placeholder: '请选择',
          itemList: [],
        },
        {
          type: 'SELECT',
          label: '品牌',
          fieldName: 'brandId',
          placeholder: '请选择',
          itemList: [],
          change: (val) => {
            this.changeBrandSelect(val);
          },
        },
        {
          type: 'SELECT',
          label: '车系',
          fieldName: 'seriesId',
          placeholder: '请选择',
          itemList: [],
          change: (val) => {
            this.changeSeriesSelect(val);
          },
        },
        {
          type: 'SELECT',
          label: '车型',
          fieldName: 'modelId',
          placeholder: '请选择',
          itemList: [],
          change: (val) => {
            this.changeModelSelect(val);
          },
        },
        {
          type: 'SELECT',
          label: '配置',
          fieldName: 'packageId',
          placeholder: '请选择',
          itemList: [],
          change: (val) => {
            this.changePackageSelect(val);
          },
        },
        {
          type: 'SELECT',
          label: '选装',
          fieldName: 'optionId',
          placeholder: '请选择',
          itemList: [],
        },
        {
          type: 'SELECT',
          // type: 'INPUT',
          label: '外饰',
          // fieldName: 'colorStr',
          fieldName: 'colorId',
          placeholder: '请选择',
          itemList: [],
        },
        {
          type: 'SELECT',
          // type: 'INPUT',
          label: '内饰',
          fieldName: 'trimColorId',
          // fieldName: 'interiorColor',
          placeholder: '请选择',
          itemList: [],
        },
        {
          type: 'INPUT',
          label: '经销商代码',
          fieldName: 'dealerCodes',
          placeholder: '输入多个经销商代码时，请用英文逗号隔开',
        },
        {
          type: 'INPUT',
          label: '经销商名称',
          fieldName: 'dealerName',
          placeholder: '请输入',
        },
        {
          type: 'RANGE_INPUT_NUMBER',
          label: '采购价格',
          fieldName: 'afterDiscountAmountMin|afterDiscountAmountMax',
          placeholder: '请输入价格',
        },
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 80,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <multiuse-button size="mini" type="text" onClick={() => this.detailHandle(props.row)}>
                  详情
                </multiuse-button>
              </div>
            );
          },
        },
        {
          title: '经销商代码',
          dataIndex: 'dealerCode',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '经销商名称',
          dataIndex: 'dealerName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '订单编号',
          dataIndex: 'orderNo',
          sorter: true,
          filter: true,
          filterType: 'input',
          align: 'center',
          width: 200,
        },
        {
          title: '结算订单编号',
          dataIndex: 'doNo',
          sorter: true,
          filter: true,
          filterType: 'input',
          align: 'center',
          width: 200,
        },
        {
          title: '订单类型',
          dataIndex: 'orderType',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('2105').filter((item) => item.value == '21051001' || item.value == '21051002'),
          render: (p) => {
            return <span>{this.createDictText(p.row.orderType, '2105')}</span>;
          },
        },
        {
          title: '订单明细类型',
          dataIndex: 'orderDetailTypeName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '紧急度',
          dataIndex: 'emergencyType',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('2101'),
          render: (p) => {
            return <span>{this.createDictText(p.row.emergencyType, '2101')}</span>;
          },
        },
        {
          title: '车辆用途',
          dataIndex: 'vehicleUse',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('2102'),
          render: (p) => {
            return <span>{this.createDictText(p.row.vehicleUse, '2102')}</span>;
          },
        },
        {
          title: '订单明细状态',
          dataIndex: 'orderStatus',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('2109').filter(
            (item) => item.value == '21091001' || item.value == '21091008' || item.value == '21091009' || item.value == '21091002' || item.value == '21091003'
          ),
          render: (p) => {
            return <span>{this.createDictText(p.row.orderStatus, '2109')}</span>;
          },
        },
        {
          title: '资金类型',
          dataIndex: 'accountId',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: true,
          editType: 'select',
          editRequired: true,
          width: 200,
          showOverflowTooltip: false,
          rules: [{ required: true, message: '请填写', trigger: 'blur' }],
          render: (p) => {
            return (
              <el-select
                size="mini"
                v-model={p.row.accountId}
                required
                placeholder="请选择"
                onChange={(value) => {
                  p.row.accountId = value;
                  for (let x of p.row.accountTypes) {
                    if (x.accountId == value) {
                      p.row.tripFund = x.tripFund;
                      p.row.isTrip = x.isTrip;
                      break;
                    }
                  }
                }}
              >
                {(p.row.accountTypes || []).map((item) => (
                  <el-option key={item.accountId} label={item.accountTypeName} value={item.accountId} />
                ))}
              </el-select>
            );
          },
        },
        {
          title: '三方使用金额',
          dataIndex: 'tripUseFund',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2,
          align: 'right',
          render: (p) => {
            return (
              <span class="discount" onClick={() => this.editHandle(p.row, 2)}>
                {this.formatNumber(Number(p.row.tripUseFund).toFixed(2))}
              </span>
            );
          },
        },
        {
          title: '自有资金余额',
          dataIndex: 'ownFund',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2,
          numberFormat: true,
          align: 'right',
        },
        {
          title: '三方可用余额',
          dataIndex: 'tripFund',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2,
          numberFormat: true,
          align: 'right',
        },
        // {
        //   title: '是否三方',
        //   dataIndex: 'isTrip',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input',
        //   hidden: true,
        // },
        {
          title: '订单年月',
          dataIndex: 'orderYearMonth',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '运输方式',
          dataIndex: 'transportType',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: true,
          editType: 'input',
          editRequired: true,
          rules: [{ required: true, message: '请填写运输方式', trigger: 'blur' }],
          render: (p) => {
            return (
              <el-select
                size="mini"
                v-model={p.row.transportType}
                placeholder="请选择"
                onChange={(value) => {
                  p.row.transportType = value;
                  p.row.addressId = '';
                  p.row.linkMan = '';
                  p.row.linkPhone = '';
                  p.row.cityName = '';
                  if (p.row.transportType === 24091002) {
                    this.changeIsCustom([p.row], true);
                    if (p.row.addressSelfDtos[0] != null && p.row.addressSelfDtos[0] !== undefined) {
                      p.row.address = p.row.addressSelfDtos[0].address;
                      p.row.addressId = p.row.addressSelfDtos[0].addressId;
                      p.row.cityName = '';
                      p.row.linkMan = '';
                      p.row.linkPhone = '';
                    }
                  } else {
                    this.changeIsCustom([p.row], false);
                    if (p.row.addressDtos[0] !== null && p.row.addressDtos[0] !== undefined) {
                      p.row.linkMan = p.row.addressDtos[0].linkMan === null ? '' : p.row.addressDtos[0].linkMan;
                      p.row.linkPhone = p.row.addressDtos[0].linkPhone === null ? '' : p.row.addressDtos[0].linkPhone;
                      p.row.cityName = p.row.addressDtos[0].cityName === null ? '' : p.row.addressDtos[0].cityName;
                      p.row.addressId = p.row.addressDtos[0].addressId;
                    }
                  }
                }}
              >
                {(this.createDictList('2409') || []).map((item) => (
                  <el-option label={item.text} value={item.value} />
                ))}
              </el-select>
            );
          },
        },
        {
          title: '收车地址',
          dataIndex: 'addressId',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: true,
          width: 180,
          editType: 'input',
          editRequired: true,
          rules: [{ required: true, message: '请填写收车地址', trigger: 'blur' }],
          render: (p) => {
            return (
              <el-select
                size="mini"
                v-model={p.row.addressId}
                required
                placeholder="请选择"
                onChange={(value) => {
                  p.row.addressId = value;
                  if (p.row.transportType === 24091002) {
                    this.changeIsCustom([p.row], true);
                    for (let x of p.row.addressSelfDtos) {
                      if (x.addressId == value) {
                        p.row.cityName = x.cityName === null ? '' : x.cityName;
                        p.row.linkMan = x.linkMan === null ? '' : x.linkMan;
                        p.row.linkPhone = x.linkPhone === null ? '' : x.linkPhone;
                        p.row.address = x.address;
                        break;
                      }
                    }
                  } else {
                    this.changeIsCustom([p.row], false);
                    for (let x of p.row.addressDtos) {
                      if (x.addressId == value) {
                        p.row.cityName = x.cityName === null ? '' : x.cityName;
                        p.row.linkMan = x.linkMan === null ? '' : x.linkMan;
                        p.row.linkPhone = x.linkPhone === null ? '' : x.linkPhone;
                        p.row.address = x.address;
                        break;
                      }
                    }
                  }
                }}
              >
                {(p.row.transportType === 24091002 ? p.row.addressSelfDtos || [] : p.row.addressDtos || []).map((item) => (
                  <el-option key={item.addressId} label={item.address} value={item.addressId} />
                ))}
              </el-select>
            );
          },
        },
        {
          title: '送达城市',
          dataIndex: 'cityName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '联系人',
          dataIndex: 'linkMan',
          sorter: true,
          filter: true,
          editable: true,
          defaultEditable: false,
          filterType: 'input',
        },
        {
          title: '联系电话',
          dataIndex: 'linkPhone',
          sorter: true,
          filter: true,
          editable: true,
          defaultEditable: false,
          filterType: 'input',
        },
        {
          title: '可用资源',
          dataIndex: 'avilableVehicles',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: (p) => {
            return <span>{p.row.avilableVehicles ? p.row.avilableVehicles : 0}</span>;
          },
        },
        {
          title: '物料编码',
          dataIndex: 'productCode',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '物料描述',
          dataIndex: 'productName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '车系',
          dataIndex: 'seriesName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '车型',
          dataIndex: 'modelName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '配置',
          dataIndex: 'packageName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '选装',
          dataIndex: 'optionName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '内饰',
          dataIndex: 'trimName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '外饰',
          dataIndex: 'colorName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '市场指导价',
          dataIndex: 'singleAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2,
          numberFormat: true,
          align: 'right',
        },

        {
          title: '现金折让',
          dataIndex: 'discountAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: true,
          editType: 'number',
          editRequired: true,
          defaultEditable: true,
          precision: 2,
          onInput: (index, data) => {
            this.changeNum(index, data);
          },
        },
        {
          title: '建店返利',
          dataIndex: 'buildRebateAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: true,
          editType: 'number',
          editRequired: true,
          defaultEditable: true,
          precision: 2,
          onInput: (index, data) => {
            this.changeNum(index, data);
          },
        },
        {
          title: '定金金额',
          dataIndex: 'orderAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2,
          numberFormat: true,
          align: 'right',
        },
        {
          title: '价格类型',
          dataIndex: 'amountType',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('2136'),
          render: (p) => {
            return <span>{this.createDictText(p.row.amountType, '2136')}</span>;
          },
        },
        {
          title: '采购价格',
          dataIndex: 'afterDiscountAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2,
          numberFormat: true,
          align: 'right',
        },
        {
          title: '是否使用返利',
          dataIndex: 'isRebate',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: true,
          editType: 'select',
          editRequired: true,
          width: 200,
          showOverflowTooltip: false,
          rules: [{ required: true, message: '请填写', trigger: 'blur' }],
          render: (p) => {
            return (
              <el-select
                size="mini"
                v-model={p.row.isRebate}
                required
                placeholder="请选择"
                onChange={(value) => {
                  p.row.isRebate = value;
                  this.changeNum(null, p.row);
                  if (p.row.isRebate === 10041002) {
                    p.row.afterDiscountAmount = Number(p.row.afterDiscountAmount) + Number(p.row.singleRebateAmount);
                    p.row.singleRebateAmount = Number(0);
                    this.changeIsRebate(p.row, true);
                  } else {
                    this.changeIsRebate(p.row, false);
                  }
                }}
              >
                {[
                  { lable: '是', value: 10041001 },
                  { lable: '否', value: 10041002 },
                ].map((item) => (
                  <el-option key={item.value} label={item.lable} value={item.value} />
                ))}
              </el-select>
            );
          },
        },
        {
          title: '返利冲抵',
          dataIndex: 'singleRebateAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: true,
          editType: 'number',
          editRequired: true,
          defaultEditable: true,
          precision: 2,
          editPattern: /(^[1-9](\d{0,7})(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/,
          onInput: (index, data) => {
            if (data.isRebate === 10041002) {
              data.singleRebateAmount = '0.00';
            }
            this.changeNum(index, data);
          },
        },

        {
          title: '提报时间',
          dataIndex: 'reportDate',
          sorter: true,
          filter: true,
          dateFormat: 'yyyy-MM-dd HH:mm:ss',
          filterType: 'date-range',
        },
        {
          title: '审核时间',
          dataIndex: 'checkDate',
          sorter: true,
          filter: true,
          dateFormat: 'yyyy-MM-dd HH:mm:ss',
          filterType: 'date-range',
        },
        {
          title: '作废原因',
          dataIndex: 'checkRamark',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '发运须知',
          dataIndex: 'deliveryRamark',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: true,
          editType: 'input',
          defaultEditable: true,
        },
        {
          title: '备注',
          dataIndex: 'remark',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: true,
          editType: 'input',
          defaultEditable: true,
        },
        {
          title: '审批报告编号',
          dataIndex: 'reportNo',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: true,
          editType: 'input',
          defaultEditable: true,
        },
      ];
    },
    changeIsRebate(row, disabled) {
      this.$refs.table.SET_CELL_DISABLED(row, 'singleRebateAmount', disabled);
    },
    changeNum(index, data) {
      data = this.resetFormatterNumber([data])[0];
      let singleAmount = 0;
      let discountAmount = 0;
      let buildRebateAmount = 0;
      let singleRebateAmount = 0;
      singleAmount = Object.is(Number(data.singleAmount), NaN) ? 0 : Number(data.singleAmount);
      discountAmount = Object.is(Number(data.discountAmount), NaN) ? 0 : Number(data.discountAmount);
      buildRebateAmount = Object.is(Number(data.buildRebateAmount), NaN) ? 0 : Number(data.buildRebateAmount);
      singleRebateAmount = Object.is(Number(data.singleRebateAmount), NaN) ? 0 : Number(data.singleRebateAmount);
      if (data.amountType === 21361005) {
        data.afterDiscountAmount = singleAmount - discountAmount - buildRebateAmount - singleRebateAmount;
      } else if (data.amountType === 21361001 || data.amountType === 21361002 || data.amountType === 21361003) {
        data.afterDiscountAmount = singleAmount * Number(data.discount) - discountAmount - buildRebateAmount - singleRebateAmount;
      } else if (data.amountType === 21361004) {
        data.afterDiscountAmount = Number(data.specialAmount) - discountAmount - buildRebateAmount - singleRebateAmount;
      }
    },
    billclose(val) {
      if (val) {
        this.fetchParams = Object.assign({}, this.fetchParams);
      }
      this.isbill = false;
    },
    rejectClose(val) {
      if (val) {
        this.isOpen = true;
        this.fetchParams = Object.assign({}, this.fetchParams);
      }
      this.isreject = false;
    },
    financeRejectClose(val) {
      if (val) {
        this.isOpen = true;
        this.fetchParams = Object.assign({}, this.fetchParams);
      }
      this.isFinanceReject = false;
    },
    async editHandle(data, type) {
      data = this.resetFormatterNumber([data])[0];
      this.billData = data;
      if (data.orderStatus == 21091001 || data.orderStatus == 21091008 || data.orderStatus == 21091009) {
        if (Number(data.afterDiscountAmount) > 0) {
          this.isbill = true;
        } else {
          this.$notify({
            title: '警告',
            message: '该订单的采购价格小于0，请先调整采购价格',
            type: 'warning',
          });
          return;
        }
      } else {
        this.$notify({
          title: '警告',
          message: '该数据的订单明细状态不能进行选择票据操作',
          type: 'warning',
        });
        return;
      }
    },
    // 获取车型车系
    async getvehicleList() {
      let res = await vehicleConfiguration(0, { isUnlimited: 10041001 });
      this.topFilterList.find((item) => item.fieldName === 'brandProductList').itemList = res.data;
    },
    selectChangeHandle(row) {
      if (row.length > 0) {
        this.isOpen = false;
        this.selectList = row || [];
      } else {
        this.isOpen = true;
        this.selectList = [];
      }
    },
    async addHandle(type) {
      this.selectList = this.resetFormatterNumber(this.selectList);
      if (type === 1) {
        //审核
        let arr = [];
        let arr1 = [];
        let arr2 = [];
        let arr3 = [];
        let arr4 = [];
        for (let i in this.selectList) {
          if (this.selectList[i].orderStatus !== 21091001 && this.selectList[i].orderStatus !== 21091008 && this.selectList[i].orderStatus !== 21091009) {
            arr.push(this.selectList[i].doNo);
          }
          if (this.selectList[i].isTrip === 10041001) {
            if (Number(this.selectList[i].afterDiscountAmount) !== Number(this.selectList[i].tripUseFund) || Number(this.selectList[i].afterDiscountAmount) <= 0) {
              arr1.push(this.selectList[i].doNo);
            }
          }
          if (Number(this.selectList[i].afterDiscountAmount) <= 0) {
            arr2.push(this.selectList[i].doNo);
          }

          console.log(this.selectList[i].addressId + '<==22222222222222222222');
          if (this.selectList[i].addressId == null || this.selectList[i].addressId == undefined || this.selectList[i].addressId == '') {
            arr4.push(this.selectList[i].doNo);
          }
          if (
            this.selectList[i].transportType === 24091002 &&
            (this.selectList[i].linkMan == null || this.selectList[i].linkMan.length == 0 || this.selectList[i].linkPhone == null || this.selectList[i].linkPhone.length == 0)
          ) {
            arr3.push(this.selectList[i].doNo);
          }
        }
        console.log(arr4, '22222222222222222222');
        if (arr.length > 0) {
          this.$notify({
            title: '警告',
            message: '以下数据不能进行{' + arr + '}保存操作',
            type: 'warning',
          });
          return;
        }
        if (arr1.length > 0) {
          this.$notify({
            title: '警告',
            message: '以下数据使用票据价格不等于采购价格{' + arr1 + '}',
            type: 'warning',
          });
          return;
        }

        if (arr2.length > 0) {
          this.$notify({
            title: '警告',
            message: '以下数据采购价格{' + arr2 + '}必须大于0',
            type: 'warning',
          });
          return;
        }

        if (arr4.length > 0) {
          this.$notify({
            title: '警告',
            message: '地址不能为空，请选择地址或切换运输方式{' + arr4 + '}',
            type: 'warning',
          });
          return;
        }
        if (arr3.length > 0) {
          this.$notify({
            title: '警告',
            message: '运输方式为自提时，联系人、联系电话必填{' + arr3 + '}',
            type: 'warning',
          });
          return;
        }

        await this.$confirm('是否确认审核订单?', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(async () => {
            let res = await confirmOrder(this.selectList);
            if (res.resultCode === 200) {
              let total = res.data.total;
              let errorTotal = res.data.errorTotal;
              let error = res.data.error;
              this.$notify({
                title: '审核状态',
                message: '审核状态：审核' + total + '条,失败' + errorTotal + '条,失败列表' + error,
                type: 'success',
              });
              // this.$notify({
              //   title: '成功',
              //   message: '审核成功',
              //   type: 'success',
              // });
              this.isOpen = true;
              this.fetchParams = Object.assign({}, this.fetchParams);
            }
          })
          .catch(() => {});
      } else if (type === 2) {
        let arr = [];
        for (let i in this.selectList) {
          if (this.selectList[i].orderStatus !== 21091001 && this.selectList[i].orderStatus !== 21091008 && this.selectList[i].orderStatus !== 21091009) {
            arr.push(this.selectList[i].doNo);
          }
        }
        if (arr.length > 0) {
          this.$notify({
            title: '警告',
            message: '以下数据不能进行{' + arr + '}作废操作',
            type: 'warning',
          });
          return;
        }
        this.isreject = true;
      } else if (type === 3) {
        //取消订单
        let arr = [];
        for (let i in this.selectList) {
          if (this.selectList[i].orderStatus !== 21091002 && this.selectList[i].orderStatus !== 21091003) {
            arr.push(this.selectList[i].doNo);
          }
        }
        if (arr.length > 0) {
          this.$notify({
            title: '警告',
            message: '以下数据不能进行{' + arr + '}取消审核操作',
            type: 'warning',
          });
          return;
        }
        await this.$confirm('是否确定取消审核订单?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(async () => {
            this.exportLoading = true;
            let res = await cancelOrder(this.selectList);
            this.exportLoading = false;
            if (res.resultCode == 200) {
              let total = res.data.total;
              let errorTotal = res.data.errorTotal;
              let error = res.data.error;
              this.$notify({
                title: '取消状态',
                message: '取消状态：取消' + total + '条,失败' + errorTotal + '条,失败列表' + error,
                type: 'success',
              });
              // this.$notify({
              //   title: '取消状态',
              //   message: '取消成功',
              //   type: 'success',
              // });
              this.isOpen = true;
              this.fetchParams = Object.assign({}, this.fetchParams);
            }
          })
          .catch(() => {
            this.exportLoading = false;
          });
      } else if (type === 5) {
        this.importVisible = true;
      } else if (type === 6) {
        let array = [],
          data = {};
        this.selectList.map((x) => {
          data[x.dealerCode] = x.dealerCode;
        });
        for (let i in data) {
          array.push(data[i]);
        }
        if (array.length > 1) {
          this.$notify({
            title: '警告',
            message: '请选择同一经销商的数据',
            type: 'warning',
          });
          return;
        } else {
          let arr = [];
          for (let i in this.selectList) {
            if (this.selectList[i].orderStatus !== 21091001 && this.selectList[i].orderStatus !== 21091008 && this.selectList[i].orderStatus !== 21091009) {
              arr.push(this.selectList[i].doNo);
            }
          }
          //console.log(arr);
          if (arr.length > 0) {
            this.$notify({
              title: '警告',
              message: '以下数据不能进行{' + arr + '}资金调整操作',
              type: 'warning',
            });
            return;
          }
        }
        this.isFundType = true;
      } else if (type === 7) {
        let array = [],
          data = {};
        this.selectList.map((x) => {
          data[x.dealerCode] = x.dealerCode;
        });
        for (let i in data) {
          array.push(data[i]);
        }
        if (array.length > 1) {
          this.$notify({
            title: '警告',
            message: '请选择同一经销商的数据',
            type: 'warning',
          });
          return;
        }
        let arr = [];
        for (let i in this.selectList) {
          if (this.selectList[i].orderStatus !== 21091001 && this.selectList[i].orderStatus !== 21091008 && this.selectList[i].orderStatus !== 21091009) {
            arr.push(this.selectList[i].doNo);
          }
        }
        if (arr.length > 0) {
          this.$notify({
            title: '警告',
            message: '以下数据状态不能进行{' + arr + '}地址调整操作',
            type: 'warning',
          });
          return;
        }
        let arr1 = [];
        for (let i in this.selectList) {
          if (this.selectList[i].transportType == 24091002 || this.selectList[i].transportType === '') {
            arr1.push(this.selectList[i].doNo);
          }
        }
        if (arr1.length > 0) {
          this.$notify({
            title: '警告',
            message: '请选择运输方式为运输的数据',
            type: 'warning',
          });
          return;
        }
        this.isAddress = true;
      } else if (type === 4) {
        //导出
        this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
          confirmButtonText: '下载',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            this.$refs.top.SUBMIT_FORM();
            // this.exportLoading = true;
            excelList(this.fetchParams)
              .then((response) => {
                exportExcelFile(response.data, '订单审核确认');
                // this.exportLoading = false;
              })
              .catch((err) => {
                //console.log(err);
              });
          })
          .catch(() => {
            // this.exportLoading = false;
            this.$message({
              type: 'info',
              message: '已取消',
            });
          });
      } else if (type === 8) {
        let arr = [];
        let arr1 = [];
        let arr2 = [];
        let arr3 = [];
        let arr4 = [];
        for (let i in this.selectList) {
          if (this.selectList[i].orderStatus !== 21091001 && this.selectList[i].orderStatus !== 21091008 && this.selectList[i].orderStatus !== 21091009) {
            arr.push(this.selectList[i].doNo);
          }
          if (this.selectList[i].isTrip === 10041001) {
            if (Number(this.selectList[i].afterDiscountAmount) !== Number(this.selectList[i].tripUseFund) || Number(this.selectList[i].afterDiscountAmount) <= 0) {
              arr1.push(this.selectList[i].doNo);
            }
          }
          if (Number(this.selectList[i].afterDiscountAmount) <= 0) {
            arr2.push(this.selectList[i].doNo);
          }

          if (this.selectList[i].addressId == null || this.selectList[i].addressId == undefined || this.selectList[i].addressId == '') {
            arr4.push(this.selectList[i].doNo);
          }
          if (
            this.selectList[i].transportType === 24091002 &&
            (this.selectList[i].linkMan == null || this.selectList[i].linkMan.length == 0 || this.selectList[i].linkPhone == null || this.selectList[i].linkPhone.length == 0)
          ) {
            arr3.push(this.selectList[i].doNo);
          }
        }
        if (arr.length > 0) {
          this.$notify({
            title: '警告',
            message: '以下数据不能进行{' + arr + '}保存操作',
            type: 'warning',
          });
          return;
        }
        if (arr1.length > 0) {
          this.$notify({
            title: '警告',
            message: '以下数据使用票据价格不等于采购价格{' + arr1 + '}',
            type: 'warning',
          });
          return;
        }

        if (arr2.length > 0) {
          this.$notify({
            title: '警告',
            message: '以下数据采购价格{' + arr2 + '}必须大于0',
            type: 'warning',
          });
          return;
        }

        if (arr4.length > 0) {
          this.$notify({
            title: '警告',
            message: '地址不能为空，请选择地址或切换运输方式{' + arr4 + '}',
            type: 'warning',
          });
          return;
        }
        if (arr3.length > 0) {
          this.$notify({
            title: '警告',
            message: '运输方式为自提时，联系人、联系电话必填{' + arr3 + '}',
            type: 'warning',
          });
          return;
        }

        await this.$confirm('是否确认保存订单?', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(async () => {
            let res = await saveOrder(this.selectList);
            if (res.resultCode === 200) {
              let total = res.data.total;
              let errorTotal = res.data.errorTotal;
              let error = res.data.error;
              this.$notify({
                title: '保存状态',
                message: '保存状态：保存' + total + '条,失败' + errorTotal + '条,失败列表' + error,
                type: 'success',
              });
              this.isOpen = true;
              this.fetchParams = Object.assign({}, this.fetchParams);
            }
          })
          .catch(() => {});
      }
    },
    FundTypeClose(val) {
      if (val) {
        this.isOpen = true;
        this.fetchParams = Object.assign({}, this.fetchParams);
      }
      this.isFundType = false;
    },
    AddressClose(val) {
      if (val) {
        this.isOpen = true;
        this.fetchParams = Object.assign({}, this.fetchParams);
      }
      this.isAddress = false;
    },
    importcloseHandler() {
      this.importVisible = false;
      this.fetchParams = Object.assign({}, this.fetchParams);
    },
    /**
     * 查看详情
     * @param data
     */
    detailHandle(data) {
      this.formData = data;
      this.detailVisible = true;
    },
    detailCloseHandler() {
      this.detailVisible = false;
      this.fetchParams = Object.assign({}, this.fetchParams);
    },
    changeHandle(params) {
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.$refs.table.$refs.pageTable.EXECUTE_RESET_HEIGHT();
      });
    },
  },
};
</script>
